<template>
  <div class="user-management">
    <div class="page-header">
      <h2>用户管理</h2>
      <p>管理系统用户信息、角色分配和权限控制</p>
    </div>
    
    <!-- 搜索和操作区 -->
    <a-card class="search-card">
      <a-form
        :model="searchForm"
        layout="inline"
        class="search-form"
      >
        <a-form-item label="用户名">
          <a-input
            v-model:value="searchForm.username"
            placeholder="请输入用户名"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="邮箱">
          <a-input
            v-model:value="searchForm.email"
            placeholder="请输入邮箱"
            allow-clear
          />
        </a-form-item>
        
        <a-form-item label="角色">
          <a-select
            v-model:value="searchForm.roleId"
            placeholder="请选择角色"
            allow-clear
            style="width: 150px"
          >
            <a-select-option value="1">管理员</a-select-option>
            <a-select-option value="2">编辑者</a-select-option>
            <a-select-option value="3">普通用户</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">
              <SearchOutlined />
              搜索
            </a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
      
      <div class="actions">
        <a-button
          type="primary"
          @click="handleAdd"
          v-if="userStore.hasPermission('system:user:add')"
        >
          <PlusOutlined />
          新增用户
        </a-button>
      </div>
    </a-card>
    
    <!-- 用户表格 -->
    <a-card class="table-card">
      <a-table
        :columns="columns"
        :data-source="userList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'avatar'">
            <a-avatar :src="record.avatar">
              {{ record.username.charAt(0).toUpperCase() }}
            </a-avatar>
          </template>
          
          <template v-if="column.key === 'roles'">
            <a-tag
              v-for="role in record.roles"
              :key="role.id"
              :color="getRoleColor(role.code)"
            >
              {{ role.name }}
            </a-tag>
          </template>
          
          <template v-if="column.key === 'createdAt'">
            {{ dayjs(record.createdAt).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          
          <template v-if="column.key === 'action'">
            <a-space>
              <a-button
                type="link"
                size="small"
                @click="handleEdit(record)"
                v-if="userStore.hasPermission('system:user:edit')"
              >
                编辑
              </a-button>
              
              <a-button
                type="link"
                size="small"
                @click="handleResetPassword(record)"
                v-if="userStore.hasPermission('system:user:reset')"
              >
                重置密码
              </a-button>
              
              <a-popconfirm
                title="确定要删除这个用户吗？"
                @confirm="handleDelete(record)"
                v-if="userStore.hasPermission('system:user:delete')"
              >
                <a-button type="link" size="small" danger>
                  删除
                </a-button>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
    
    <!-- 用户编辑模态框 -->
    <EnterpriseModal
      v-model:open="modalVisible"
      :title="modalTitle"
      width="600"
      @ok="handleSubmit"
      @cancel="handleCancel"
      :confirm-loading="submitLoading"
    >
      <a-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="用户名" name="username">
          <a-input v-model:value="formData.username" placeholder="请输入用户名" />
        </a-form-item>
        
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formData.email" placeholder="请输入邮箱" />
        </a-form-item>
        
        <a-form-item label="头像" name="avatar">
          <a-input v-model:value="formData.avatar" placeholder="请输入头像URL" />
        </a-form-item>
        
        <a-form-item label="角色" name="roleIds">
          <a-select
            v-model:value="formData.roleIds"
            mode="multiple"
            placeholder="请选择角色"
            style="width: 100%"
          >
            <a-select-option value="1">管理员</a-select-option>
            <a-select-option value="2">编辑者</a-select-option>
            <a-select-option value="3">普通用户</a-select-option>
          </a-select>
        </a-form-item>
        
        <a-form-item label="密码" name="password" v-if="!isEdit">
          <a-input-password v-model:value="formData.password" placeholder="请输入密码" />
        </a-form-item>
      </a-form>
    </EnterpriseModal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import {
  SearchOutlined,
  PlusOutlined
} from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { useUserStore } from '@/stores/user'
import { getUserList, createUser, updateUser, deleteUser, resetPassword } from '@/api/user'
import { EnterpriseModal } from '@/components'
import dayjs from 'dayjs'
import type { User, UserPageParams } from '@/types/user'
import type { TableColumnsType } from 'ant-design-vue'

const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const submitLoading = ref(false)
const modalVisible = ref(false)
const isEdit = ref(false)
const formRef = ref()

const searchForm = reactive<Partial<UserPageParams>>({
  username: '',
  email: '',
  roleId: undefined
})

const userList = ref<User[]>([])
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条记录`
})

const formData = reactive({
  id: undefined as number | undefined,
  username: '',
  email: '',
  avatar: '',
  roleIds: [] as string[],
  password: ''
})

const modalTitle = computed(() => isEdit.value ? '编辑用户' : '新增用户')

// 表格列定义
const columns: TableColumnsType = [
  {
    title: 'ID',
    dataIndex: 'id',
    key: 'id',
    width: 80
  },
  {
    title: '头像',
    key: 'avatar',
    width: 80
  },
  {
    title: '用户名',
    dataIndex: 'username',
    key: 'username'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    key: 'email'
  },
  {
    title: '角色',
    key: 'roles'
  },
  {
    title: '创建时间',
    key: 'createdAt',
    width: 180
  },
  {
    title: '操作',
    key: 'action',
    width: 200
  }
]

// 表单验证规则
const formRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '用户名长度在2-20字符之间', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  roleIds: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

// 获取角色颜色
const getRoleColor = (roleCode: string) => {
  const colors = {
    admin: 'red',
    editor: 'blue',
    user: 'green'
  }
  return colors[roleCode as keyof typeof colors] || 'default'
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  loadUserList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    username: '',
    email: '',
    roleId: undefined
  })
  pagination.current = 1
  loadUserList()
}

// 表格变化处理
const handleTableChange = (pag: any) => {
  pagination.current = pag.current
  pagination.pageSize = pag.pageSize
  loadUserList()
}

// 新增用户
const handleAdd = () => {
  isEdit.value = false
  modalVisible.value = true
  resetForm()
}

// 编辑用户
const handleEdit = (record: User) => {
  isEdit.value = true
  modalVisible.value = true
  Object.assign(formData, {
    id: record.id,
    username: record.username,
    email: record.email,
    avatar: record.avatar || '',
    roleIds: record.roles.map(role => role.id.toString()),
    password: ''
  })
}

// 删除用户
const handleDelete = async (record: User) => {
  try {
    await deleteUser(record.id)
    message.success('删除成功')
    loadUserList()
  } catch (error: any) {
    message.error(error.message || '删除失败')
  }
}

// 重置密码
const handleResetPassword = (record: User) => {
  Modal.confirm({
    title: '重置密码',
    content: `确定要重置用户"${record.username}"的密码吗？`,
    onOk: async () => {
      try {
        await resetPassword(record.id, '123456')
        message.success('密码重置成功，新密码为：123456')
      } catch (error: any) {
        message.error(error.message || '重置密码失败')
      }
    }
  })
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitLoading.value = true
    
    if (isEdit.value && formData.id) {
      await updateUser(formData.id, formData)
      message.success('更新成功')
    } else {
      await createUser(formData)
      message.success('创建成功')
    }
    
    modalVisible.value = false
    loadUserList()
  } catch (error: any) {
    message.error(error.message || '操作失败')
  } finally {
    submitLoading.value = false
  }
}

// 取消编辑
const handleCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 重置表单
const resetForm = () => {
  Object.assign(formData, {
    id: undefined,
    username: '',
    email: '',
    avatar: '',
    roleIds: [],
    password: ''
  })
  formRef.value?.resetFields()
}

// 加载用户列表
const loadUserList = async () => {
  try {
    loading.value = true
    const params: UserPageParams = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    
    // 模拟API调用，实际项目中这里会调用真实API
    const mockData = {
      list: [
        {
          id: 1,
          username: 'admin',
          email: 'admin@example.com',
          avatar: '',
          roles: [{ id: 1, name: '管理员', code: 'admin', permissions: [] }],
          permissions: ['dashboard:view', 'system:user:view', 'system:user:add', 'system:user:edit', 'system:user:delete', 'system:user:reset'],
          createdAt: '2024-01-01 10:00:00',
          updatedAt: '2024-01-01 10:00:00'
        },
        {
          id: 2,
          username: 'editor',
          email: 'editor@example.com',
          avatar: '',
          roles: [{ id: 2, name: '编辑者', code: 'editor', permissions: [] }],
          permissions: ['dashboard:view', 'system:user:view'],
          createdAt: '2024-01-02 10:00:00',
          updatedAt: '2024-01-02 10:00:00'
        }
      ],
      total: 2,
      current: 1,
      pageSize: 10
    }
    
    userList.value = mockData.list
    pagination.total = mockData.total
  } catch (error: any) {
    message.error(error.message || '获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  loadUserList()
})
</script>

<style scoped>
.user-management {
  padding: 0;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #262626;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
}

.search-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
}

.actions {
  margin-top: 16px;
  text-align: right;
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

:deep(.ant-table-thead > tr > th) {
  background: #fafafa;
  font-weight: 600;
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}
</style> 